<?php

namespace App\Http\Controllers;

use App\Http\Requests\CardItemRequest;
use App\Models\CartItem;
use App\Models\ProductSku;
use Illuminate\Http\Request;

class CartController extends Controller
{
    //
    public function add(CardItemRequest $request): array
    {
        $user = $request->user();
        $skuId = $request->sku_id;
        $amount = $request->amount;
        //查询用户购物车是否有当前sku
        if ($cartItem = $user->cartItems()->where('product_sku_id', $skuId)->first()) {
            $cartItem->amount += $amount;
            $cartItem->save();
        }else {
            (new CartItem([
                'user_id' => $user->id,
                'product_sku_id' => $skuId,
                'amount' => $amount,
            ]))->save();
        }
        return [];
    }

    public function index(Request $request)
    {
        $cartItems = $request->user()->cartItems()->with('productSku.product')->get();
        $addresses = $request->user()->addresses()->orderByDesc('last_used_at') ->get();
        return view('cart.index', compact('cartItems','addresses'));
    }

    public function remove(ProductSku $sku, Request $request): array
    {
        $request->user()->cartItems()->where('product_sku_id', $sku->id)->delete();
        return [];
    }
}
